#!/usr/bin/python

import math
from eulerlib import number;


nlimit=10**7-1;


#used in permutation checker
primes=[2,3,5,7,11,13,17,19,23,29];
reciprimes=map( (lambda x: 1.0/x), primes);


def permutationCheck(x, y):
	checker=1;
	while x>0:
		checker*=primes[x%10];
		x/=10;
	
	while y>0:
		checker*=reciprimes[y%10];
		y/=10;

	return (checker==1);
		


def gentotientlist(limit):
	sieve=range(limit+1);
	
	sieve[1]=0;

	for x in xrange(2,limit):
		if sieve[x]==x:# x is prime
			sieve[x]=x-1.0;
			mult=(1.0-1.0/x);
			y=x+x;
			while(y<=limit):
				sieve[y]*=mult;
				y+=x;
	return sieve;


def euler70():
	totient=gentotientlist(nlimit);
	
	minratio=nlimit;
	bestn=0;

	for n in xrange(2,nlimit+1):
		if( float(n)/totient[n] < minratio and permutationCheck(int(n), int(totient[n]))):
			minratio=float(n)/totient[n];
			bestn=n;	

	return bestn;


print euler70();


